package com.xci.platform.auth.service;

import com.xci.platform.auth.core.AuthHelper;
import com.xci.platform.auth.core.HistoryModel;
import com.xci.platform.auth.core.LogModel;
import com.xci.platform.auth.core.LogOperateType;
import com.xci.platform.auth.entity.HistoryEntity;
import com.xci.platform.auth.entity.LogEntity;
import com.xci.platform.helper.JsonHelper;
import com.xci.platform.helper.StringHelper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限子系统服务基类
 */
public class AuthBaseService {

    /**
     * 日志服务
     */
    @Resource
    private LogService logService;

    /**
     * 历史记录服务
     */
    @Resource
    private HistoryService historyService;

    protected HttpServletRequest getRequest() {
        ServletRequestAttributes servlet = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servlet != null) {
            return servlet.getRequest();
        }
        return null;
    }

    protected HttpServletResponse getResponse() {
        ServletRequestAttributes servlet = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servlet != null) {
            return servlet.getResponse();
        }
        return null;
    }

    /**
     * 添加系统操作日志
     *
     * @param module      模块
     * @param message     操作消息
     * @param costTime    执行耗时
     */
    void operateLog(String module, String message, long costTime) {
        LogModel logModel = new LogModel();
        logModel.setOperateType(LogOperateType.Operate);
        logModel.setResult(true);
        logModel.setModule(module);
        logModel.setMessage(message);
        logModel.setCostTime(costTime);

        LogEntity entity = AuthHelper.buildLogInfo(getRequest(), logModel);
        logService.insert(entity);
    }

    /**
     * 添加历史记录操作日志
     * @param historyBuilder 历史记录对象
     */
    void operateHistory(HistoryModel.HistoryModelBuilder historyBuilder) {
        HistoryModel model = historyBuilder.build();
        HistoryEntity entity = new HistoryEntity();
        entity.setId(StringHelper.guid());
        entity.setTableName(model.getTableName());
        entity.setTableCaption(model.getTableCaption());
        entity.setKeyName(model.getKeyName());
        entity.setKeyValue(model.getKeyValue());
        entity.setBeforeData(JsonHelper.serialize(model.getBefore(),true));
        entity.setAfterData(JsonHelper.serialize(model.getAfter(),true));
        entity.setMessage(model.getMessage());
        entity.setOperateType(model.getOperateType().getId());

        historyService.insert(entity);
    }
}
